<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
	xmlns:fn="fn" xmlns:xs="http://www.w3.org/2001/XMLSchema" version="2.0"
	exclude-result-prefixes="xs fn">

	<xsl:output indent="yes" encoding="UTF-8" />

	<xsl:param name="pathToCSV"
		select="'file:///home/gary/dev/etg/sauv/xslt/CSV2KML/files/csv/20120326-120258.Sauv02-seatweet.000.csv'" />
	<xsl:param name="pathToXML"
		select="'file:///home/gary/dev/etg/sauv/xslt/CSV2KML/files/xml/20120326-120258.Sauv02-seatweet.000.xml'" />

	<xsl:function name="fn:getTokens" as="xs:string+">
		<xsl:param name="str" as="xs:string" />
		<xsl:analyze-string select="concat($str, ',')" regex='(("[^"]*")+|[^,]*),'>
			<xsl:matching-substring>
				<xsl:sequence select='replace(regex-group(1), "^""|""$|("")""", "$1")' />
			</xsl:matching-substring>
		</xsl:analyze-string>
	</xsl:function>

	<xsl:template match="/" name="main">
		<xsl:result-document href="{$pathToXML}"> <!-- Added result document tag GSH -->
			<xsl:choose>
				<xsl:when test="unparsed-text-available($pathToCSV, 'UTF-8')">
					<xsl:variable name="csv" select="unparsed-text($pathToCSV, 'UTF-8')" />
					<!-- GSH: note that I've changed the tokenize statement to '\r?\n' rather 
						than ' ' as per http://www.w3.org/TR/xslt20/#regular-expressions -->
					<xsl:variable name="lines" select="tokenize($csv, '\r?\n')"
						as="xs:string+" />
					<xsl:variable name="elemNames" select="fn:getTokens($lines[1])"
						as="xs:string+" />
					<mission>
						<xsl:for-each select="$lines[position() > 1]">
						    <xsl:variable name="lineItems" select="fn:getTokens(.)" as="xs:string+" />
						    <xsl:choose>
				                <xsl:when test="last() != position()">
							        <point>
								        <xsl:for-each select="$elemNames">
									        <xsl:variable name="pos" select="position()" />
									        <xsl:variable name="sNodeName">
										         <xsl:copy-of select="translate(.,' %' ,'__')"/>
									        </xsl:variable>
									        <xsl:element name="{$sNodeName}">
										        <xsl:value-of select="$lineItems[$pos]" />
									        </xsl:element>
								        </xsl:for-each>
							        </point>
							    </xsl:when>
                                <xsl:otherwise></xsl:otherwise>
                            </xsl:choose>
						</xsl:for-each>
					</mission>
				</xsl:when>
				<xsl:otherwise>
					<xsl:text>Cannot locate : </xsl:text>
					<xsl:value-of select="$pathToCSV" />
				</xsl:otherwise>
			</xsl:choose>
		</xsl:result-document>
	</xsl:template>
</xsl:stylesheet>
